pip install requests # 用于发送网络请求
pip install openai
import json
import requests
# 用户user 向llm提问，让大模型处理，对于实时性，llm无法回答，所以我们要借助外部工具来辅助llm大模型。
from openai import OpenAI
client= OpenAI(
api_key='sk-28be706a9f22424cb2ca66b80ac1b523',
base_url='https://api.deepseek.com/v1'
)
message=[{"role":"user","content":"微软股票的日内交易数据"}]
response= client.chat.completions.create(
    model='deepseek-reasoner',
    messages=message,
    tools=tools,
    tool_choice="auto",
    temperature=0.1
)
response1=response.choices[0].message
print(response1)
message.append(response1)
if response1.tool_calls:
    tool_call=response1.tool_calls[0]# 从工具列表调用第一个工具
    args= json.loads(tool_call.function.arguments)
    name1=args.get("symbol")
    result=get_intraday_stock_data(name1)
    #print(result)
    
    
    
# 继续使用之前已经成功的get_intraday_stock_data函数
if response1.tool_calls:
    tool_call = response1.tool_calls[0]
    args = json.loads(tool_call.function.arguments)
    symbol = args.get("symbol")
    
    # 获取股票数据
    result = get_intraday_stock_data(symbol)
    # print("获取到的股票数据:", result)
    
    # 将股票数据传递给大模型进行分析
    tool_message = {
        "role": "tool",
        "tool_call_id": tool_call.id,
        "content": json.dumps(result)
    }
    message.append(tool_message)
    
    # 获取大模型的分析结果
    final_response = client.chat.completions.create(
        model='deepseek-reasoner',
        messages=message,
        temperature=0.1
    )
    
    final_answer = final_response.choices[0].message.content
    print("=== 微软股票分析报告 ===")
    print(final_answer)




    # 直接分析您已经获取的数据
def analyze_stock_performance(data):
    """分析股票表现"""
    time_series = data.get('Time Series (5min)', {})
    
    if not time_series:
        return "无法获取有效的股票数据"
    
    # 获取时间戳列表
    timestamps = list(time_series.keys())
    
    # 最新数据
    latest_timestamp = timestamps[0]
    latest_data = time_series[latest_timestamp]
    latest_price = float(latest_data['4. close'])
    
    # 今日开盘数据（假设第一个数据是开盘）
    open_timestamp = timestamps[-1]
    open_data = time_series[open_timestamp]
    open_price = float(open_data['1. open'])
    
    # 计算涨跌幅
    change = latest_price - open_price
    change_percent = (change / open_price) * 100
    
    # 获取最高价和最低价
    high_prices = [float(data['2. high']) for data in time_series.values()]
    low_prices = [float(data['3. low']) for data in time_series.values()]
    
    day_high = max(high_prices)
    day_low = min(low_prices)
    
    # 生成分析报告
    analysis = f"""
微软(MSFT)股票今日表现分析：
--------------------------------
📈 当前价格: ${latest_price:.2f}
🟢 今日开盘: ${open_price:.2f}
📊 涨跌幅: {change:+.2f} ({change_percent:+.2f}%)
🔺 今日最高: ${day_high:.2f}
🔻 今日最低: ${day_low:.2f}
⏰ 最后更新: {latest_timestamp}
--------------------------------
"""
    
    if change > 0:
        analysis += "🎯 今日表现: 上涨趋势"
    else:
        analysis += "🎯 今日表现: 下跌趋势"
    
    return analysis

# 直接分析您已经获取的数据
analysis_result = analyze_stock_performance(result)# 传参数
print("=== 微软股票分析报告 ===")
print(analysis_result)
import requests

def get_intraday_stock_data(symbol, interval='5min', api_key='SS00X8SPAFEGSKXP'):
    """
    获取股票日内数据
    """
    base_url = "https://www.alphavantage.co/query"
    
    params = {
        'function': 'TIME_SERIES_INTRADAY',
        'symbol': symbol,
        'interval': interval,
        'apikey': api_key,
        'outputsize': 'compact',  # 或 'full'
        'datatype': 'json'
    }
    
    response = requests.get(base_url, params=params)
    data = response.json()
    
    return data
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_intraday_stock_data",
            "description": "获取指定股票的日内交易数据",
            "parameters": {
                "type": "object",
                "properties": {
                    "symbol": {
                        "type": "string",
                        "description": "股票代码，例如：AAPL（苹果）、IBM（国际商业机器）",
                    },
                    "interval": {
                        "type": "string",
                        "enum": ["1min", "5min", "15min", "30min", "60min"],
                        "description": "数据时间间隔，默认为5分钟",
                    }
                },
                "required": ["symbol"],
            },
        },
    }
]